package com.smartdot.bluetoothidcarddemo.http;

import android.content.Context;

import com.smartdot.bluetoothidcarddemo.bean.HttpResult;
import com.smartdot.bluetoothidcarddemo.view.LoadingDialog;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;


/**
 * 订阅者封装（用于返回的BaseModel为HttpResult的请求）
 * 可在onSubscribe中进行请求前的操作，注意，onSubscribe是执行在 subscribe() 被调用时的线程，所以如果在onSubscribe里进行UI操作，就要保证subscribe()也是调用在UI线程里。
 * Created by LUOLI on 2017/6/19.
 */

public abstract class ProgressObserver<T> implements Observer<HttpResult<T>> {

    private LoadingDialog mLoadingDialog;

    private String mText;
    protected boolean showDialog = false;

    public ProgressObserver(Context context) {
        this(context, false);
    }

    public ProgressObserver(Context context, boolean show) {
        this(context, show, "");
    }

    public ProgressObserver(Context context, boolean show, String text) {
        this.showDialog = show;
        this.mText = text;
        mLoadingDialog = new LoadingDialog(context);
        showProgressDialog();
    }

    /**
     * 显示Loading
     */
    private void showProgressDialog() {
        if (mLoadingDialog != null && showDialog) {
            if (mText != null) {
                mLoadingDialog.setText(mText);
            }
            mLoadingDialog.show();
        }
    }

    /**
     * 隐藏Loading
     */
    public void dismissProgressDialog() {
        if (mLoadingDialog != null && showDialog)
            mLoadingDialog.dismiss();
    }


    @Override
    public void onSubscribe(Disposable d) {
    }

    @Override
    public void onComplete() {
        dismissProgressDialog();
    }

    @Override
    public void onError(Throwable e) {
        dismissProgressDialog();
        if (e instanceof Exception) {
            //访问获得对应的Exception
            ExceptionHandler.ResponseThrowable responseThrowable = ExceptionHandler.handleException(e);
            onError_(responseThrowable.code, responseThrowable.message,e);
        } else {
            //将Throwable 和 未知错误的status code返回
            ExceptionHandler.ResponseThrowable responseThrowable = new ExceptionHandler.ResponseThrowable(e, ExceptionHandler.ERROR.UNKNOWN);
            onError_(responseThrowable.code, responseThrowable.message,e);
        }
    }

    @Override
    public void onNext(HttpResult<T> httpResult) {
        // 正常回调
        onNext_(httpResult.getSubjects());
    }

    //具体实现下面两个方法，便可从中得到更直接详细的信息
    public abstract void onNext_(T t);

    public abstract void onError_(int errType, String errMessage,Throwable e);
}
